import time
import re
import json
import urllib
import scrapy
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
import math
import base64
from urllib.parse import urlencode


class spider(BaseTaxPolicySpider):
    name = "dalian_dlswfdsrmzf1"

    province: str = "辽宁省"  # 取表格
    city: str = "大连市"  # 取表格
    county: str = "瓦房店市"  # 取表格
    park: str = "None"  # 取表格
    source: str = "大连市瓦房店市人民政府"  # 取表格 同一个来源合并
    url: str = "https://www.dlwfd.gov.cn/xxgk/fzfg/zfbgswj/"  # 注明入口网址，以便后续排错

    def start_requests(self):
        url = "https://www.dlwfd.gov.cn/xxgk/fzfg/zfbgswj/"

        # 构造POST请求
        yield scrapy.Request(url=url, callback=self.detail_requests)

    def detail_requests(self, response, **kwargs):
        # 取链接
        links = response.xpath("//ul[@class='large-list']//a[1]/@href").getall()
        title_name_list = response.xpath("//ul[@class='large-list']//a[1]/@title").getall()
        date_list = response.xpath("//ul[@class='large-list']//span[2]/text()").getall()
        if len(title_name_list) == len(date_list) and len(title_name_list) == len(links):
            for i in range(len(title_name_list)):
                # print(title_name_list[i], date_list[i], links[i])
                if 'http' not in links[i]:
                    links[i] = f'https://www.dlwfd.gov.cn/{links[i]}'
                yield scrapy.Request(links[i], callback=self.parse_detail,
                                     meta={'title': title_name_list[i], 'date': date_list[i]})
        else:
            raise ("出错了")

        # 翻页逻辑
        if response.meta.get("is_next") is not False:
            pattern = r'页次：<b><font color="red">1</font>/(.*?)</b>'
            match = re.search(pattern, response.text)
            pages = int(match.group(1))
            if pages > 1:
                print("总页数：", pages)
                for page in range(2, pages + 1):
                    print("当前页：", page)
                    url = f"https://www.dlwfd.gov.cn/xxgk/fzfg/zfbgswj/{page}.html"
                    yield scrapy.Request(url=url, callback=self.detail_requests, meta={"is_next": False})

    def parse_list(self, response, **kwargs):
        pass

    def parse_detail(self, response, **kwargs):
        item = Item()
        item['title'] = response.meta.get('title')
        item['source_url'] = response.url
        item['publish_date'] = response.meta.get('date')
        item['content'] = response.xpath(""".""").get()
        item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        # print("item", item)
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl dalian_dlswfdsrmzf1".split())
